package org.peoples.ui.rooms {
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.controls.Label;
	import mx.controls.Text;
	import mx.core.EdgeMetrics;
	
	import org.peoples.Peoples;
	import org.peoples.rooms.RoomProperties;
	import org.peoples.ui.containers.BeveledPanel;
	
	[Style(name="panelStyleName", type="String", inherit="yes")]
	[Style(name="usersStyleName", type="String", inherit="yes")]
	[Bindable]
	public class LobbyRoomPanel extends Canvas {
		
		private var holder:BeveledPanel;
		private var txt_description:Text;
		private var txt_users:Label;
		
		private var _room:RoomProperties;
		
		public function LobbyRoomPanel() {
			
			super();
			
			addEventListener(MouseEvent.CLICK, joinRoom, false, 0, true);
			
		}
		
		override protected function createChildren():void {
			super.createChildren();
			
			if (!holder) {
				holder = new BeveledPanel();
				addChild(holder);
			}
			
			if (!txt_description) {
				txt_description = new Text();
				txt_description.selectable = false;
				holder.addChild(txt_description);
			}
			
			if (!txt_users) {
				txt_users = new Label();
				addChild(txt_users);
			}
		}
		
		override protected function commitProperties():void {
			super.commitProperties();
			
			if (this._room) {
				txt_description.text = this._room.description;
				
				txt_users.styleName = getStyle("usersStyleName");
				txt_users.text = this._room.users.size() + " Users";
				
				holder.title = this._room.name;
				holder.styleName = getStyle("panelStyleName");
			}
			
			invalidateDisplayList();
		}
		
		private function joinRoom(evt:MouseEvent):void {
			var rooms:ArrayCollection = Peoples.getInstance().joinedRooms;
			if (!rooms.contains(this._room.name)) {
				rooms.addItem(this._room.name);
			}
		}
		
		override protected function measure():void {
			super.measure();
			
			measuredMinWidth = 50;
			measuredMinHeight = 50;
			
			measuredWidth = 250;
			measuredHeight = 200;
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			holder.width = unscaledWidth;
			holder.height = unscaledHeight;
			
			var vm:EdgeMetrics = holder.viewMetricsAndPadding;
			
			txt_users.text = "0 Users";
			txt_users.x = holder.width - vm.right - txt_users.width;
			txt_users.y = holder.height - vm.bottom - txt_users.height;
			
			txt_description.x = vm.left;
			txt_description.y = vm.top;
			txt_description.width = holder.width - vm.left - vm.right;
			txt_description.maxHeight = txt_users.y - txt_description.y - 10;
		}
		
		public function get room():RoomProperties {
			return this._room;
		}
		public function set room(value:RoomProperties):void {
			this._room = value;
			
			invalidateProperties();
		}
		
	}
	
}